package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.vos.LoginVo;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) throws Exception {
        //1. 获取手机号和密码
        String name = dto.getName();
        String password = dto.getPassword();

        //2. 判断手机号或密码是否为空,为空返回0生成的jwt
        if (StringUtils.isEmpty(name) && StringUtils.isEmpty(password)){
            String token = AppJwtUtil.getToken(0L);
            return ResponseResult.okResult(token);
        }

        //2. 根据名称查询用户
        WmUser wmUser = this.lambdaQuery().eq(WmUser::getName, name).one();
        if (wmUser == null){
            throw new Exception("手机号或密码错误");
        }

        //3. 校验是否禁用
        if (wmUser.getStatus().equals(1)){
            throw new Exception("用户被冻结");
        }

        //4. 校验密码
        // if (!passwordEncoder.matches(password,apUser.getPassword())){
        //     throw new Exception("用户名或密码错误");
        // }
        boolean checkpw = BCrypt.checkpw(password, wmUser.getPassword());

        if (!BCrypt.checkpw(password,wmUser.getPassword())){
            throw new Exception("用户名或密码错误");
        }

        //5. 生成token
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));

        //6. 封装返回数据
        Map<String,Object> userMap = new HashMap<>();
        userMap.put("id",wmUser.getId());
        userMap.put("name",wmUser.getName());
        userMap.put("phone",wmUser.getPhone());
        LoginVo loginVo = new LoginVo();
        loginVo.setUser(userMap);
        loginVo.setToken(token);
        return ResponseResult.okResult(loginVo);
    }
}